import router from "../router/router";
import NProgress from "nprogress";
import "nprogress/nprogress.css";

NProgress.configure({ showSpinner: false }); // 禁用进度环

const whiteList = ["/login", "/404"]; // 白名单

router.beforeEach((to, from, next) => {
  NProgress.start();
  const role = [];
  const token = JSON.parse(sessionStorage.getItem("token"));

  if (token) {
    document.title =
      to.meta.title !== '' ? to.meta.title + ' - ' + token.username : to.name
      // to.meta.title !== '' ? to.meta.title + ' - ' + token.personName : to.name
    // for (let i = 0; i < token.userRole.length; i++) {
    //   const obj = token.userRole[i]
    //   role.push(obj)
    // }
    if (to.path === "/login") {
      NProgress.done();
      next({ path: "/" });
    } else if (hasPermission(role, to)) {
      next();
    } else {
      NProgress.done();
      next("/404");
    }
  } else {
    if (whiteList.includes(to.path)) {
      NProgress.done();
      next();
    } else {
      NProgress.done();
      next("/login");
    }
  }
});

router.afterEach(() => {
  NProgress.done();
});

function hasPermission(role, route) {
  if (route.meta && route.meta.roles) {
    return role.some(role => route.meta.roles.includes(role));
  } else {
    return true;
  }
}
